const app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}

//验证是否是手机号码
function vailPhone(number) {
  let flag = false;
  let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (number.length != 11) {
    flag = flag;
  } else if (!myreg.test(number)) {
    flag = flag;
  } else {
    flag = true;
  }
  return flag;
}

//授权验证
function authori2(url) {
  console.log(url);
  // 查看是否授权
  wx.getSetting({
    success: function (res) {
      if (!res.authSetting['scope.userInfo']) {// 未授权
        var s = "";
        if (url.path) {//url参数判断
          if (JSON.stringify(url.query) != "{}") {
            let query = url.query;
            s = JSON.stringify(query)
            url = "/" + url.path
          } else {
            url = "/" + url.path;
          }
        } else {
          url = "pages/index/index"
        }
        var firstUrl = url.substr(0, 1);
        if (firstUrl == "/") {
          url = url.substr(1);
        }
        wx.redirectTo({
          url: "/pages/authori/index?back=" + url + "&query=" + s,
        })
      } else {
        if (JSON.stringify(url.query) != "{}" && url.path == "pages/index/index") {
          wx.setStorageSync("cardId", url.query.id)
        } else {
          var cardId = wx.getStorageSync("cardId")
          if (cardId == "" || cardId == null) {
            wx.reLaunch({
              url: '/pages/weijieke/cardList/index',
            })
          }
        }
      }
    }
  })
}
//授权验证(登陆规范修改后的)
function authori(url) {
  console.log(url);
  let params = decodeURIComponent(url.query.scene);
  if (url.path == "pages/index/index") {
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let param = '';//参数
      let plist = '';
      if (params.indexOf('p-') != -1) {
        param = params.match(/p-(\S*)/)[1];//参数
        plist = param.toString().split('_');
      } else {
        param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      if (plist[0]) {
        wx.setStorageSync("cardId", plist[0]);
      }
    } else {
      if (JSON.stringify(url.query) != "{}") {
        if (url.query.id && url.query.id != 'undefined') {
          wx.setStorageSync("cardId", url.query.id)
        }
      } else {
        var cardId = wx.getStorageSync("cardId")
        if (cardId == "" || cardId == null) {
          wx.reLaunch({
            url: '/pages/weijieke/cardList/index',
          })
        }
      }
    }
  }
}
//授权验证(登陆规范修改后的)
function isAccredit(cb) {
  let isAccredit = false;
  var app = getApp();
  console.log(app.globalData.userInfo);
  if (app.globalData.userInfo.Avatar.indexOf('userdefault.png') == -1) {
    isAccredit = true;
  }
  cb(isAccredit);
  // 查看是否授权
  // wx.getSetting({
  //   success: function (res) {
  //     if (res.authSetting['scope.userInfo']) { // 已授权
  //       isAccredit = true;
  //     }
  //     cb(isAccredit);
  //   }
  // })
}

/**
 * 会员的操作记录
 * 参数actionType:2 转发名片, 3 复制微信, 7 保存电话, 9 拨打电话
 */
function aiCardActionRecord(actionType, actionValue = "") {
  var app = getApp();
  var cardId = wx.getStorageSync("cardId");
  if (!app.globalData.userInfo) {
    return;
  }
  wx.request({
    url: app.globalData.host + '/api/BusinessCard/AddAiCardAction?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&actionType=' + actionType + '&actionValue=' + encodeURIComponent(actionValue) + '&storeId=' + app.globalData.storeId + "&storeAppId=" + app.globalData.storeAppId,
    success: function (res) {
      if (res.data.Code == 0) {
        console.log(actionType + "," + actionValue)
      }
    },
  })
}

/**
 * 发送表单id
 * 参数formid
 */
function addFormIdMsg(formid) {
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/WeApp/AddFormId?uid=' + app.globalData.userInfo.Uid + '&formId=' + formid,
    success: function (res) {
      if (res.data.Code == 0) {

      }
    },
  })
}

//判断两个时间比较大小
function compareDate(d1, d2) {
  return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//当前时间获取
function getCurrentToday() {
  const date = new Date()
  var year = date.getFullYear();
  var mouths = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
  var day = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
  var hours = date.getHours();
  var Minutes = date.getMinutes(); //当前分
  var currentdate = year + "-" + mouths + "-" + day + "\t" + hours + ":" + Minutes;
  return currentdate
}

/**
 * 传入时间后几天
 * param：传入时间：dates:"2018-04-02",later:往后多少天
 */
function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  dateObj.dates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "月" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate()) + "日";
  dateObj.newdates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.year = date.getFullYear();
  dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.week = show_day[day];
  return dateObj;
}

//获取手机号
function getMobile(e) {
  var app = getApp();
  wx.login({
    success: function (res) {
      var code = res.code;
      wx.request({
        url: app.globalData.host + '/api/account/getphonenumber?encryptedData=' + encodeURIComponent(e.detail.encryptedData) + '&iv=' + encodeURIComponent(e.detail.iv) + '&storeid=' + app.globalData.storeId + '&storeAppId=' + app.globalData.storeAppId + "&code=" + code,
        success: function (res) {
          if (res.data.Code == 0) {
            app.globalData.userInfo.Mobile = res.data.Data;
            wx.setStorageSync("mobile", res.data.Data)
          }
        },
      })
    }
  })
}

//图片路径拼接
function formatAvater(avater, imgPath) {
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return imgPath + avater;
  }
}

//记录产品和商圈停留时间
function recordActionTime(startDate, actionType, typeId) {
  var app = getApp();
  var that = this;
  var cardId = wx.getStorageSync("cardId")
  var endDate = formatTime(new Date());
  var d1 = new Date(startDate);
  var d2 = new Date(endDate);
  console.log("两个时间差的秒数")
  console.log(parseInt(d2 - d1) / 1000); //两个时间相差的秒数
  var seconds = parseInt(d2 - d1) / 1000
  let uid = app.globalData.friendUid;
  if (!uid) {
    uid = app.globalData.userInfo.Uid;
  }
  var data = {
    storeId: app.globalData.storeId,
    staffId: cardId,
    actionType: actionType, //会员的操作(5 查看商圈,22 查看产品详情)
    typeId: typeId, //操作对应的ID (actiontype=5 商圈ID, actiontype=22 产品ID)
    seconds: seconds, //记录时间秒
    uid: uid
  }
  wx.request({
    url: app.globalData.host + '/api/BusinessCard/AddActionTime',
    data: data,
    success: function (res) {
      console.log(res)
    },
  })
}

// 订阅消息弹窗tmplIds: ['SqYIxjDQYQTyXbQQ5V9pLBdpOuFrks7IFq-ekRpInxw', 'J2IkN2t8Bb_YkDIaNP29x1YW71qK6FdjcPFzIUqW4Lo'],
function subscribe() {
  var app = getApp();
  wx.request({
    url: app.globalData.host + '/api/weapp/GetTemplateId?storeAppId=' + app.globalData.storeAppId,
    success: function (res) {
      let tmplIds = res.data.Data.tmplIds;
      let newTemplate = [];
      if (tmplIds.length > 3) {
        for (let i = 0; i < tmplIds.length; i++) {
          newTemplate.push(tmplIds[i]);
        }
      } else {
        newTemplate = tmplIds;
      }
      if (newTemplate.length > 0) {
        wx.requestSubscribeMessage({
          tmplIds: newTemplate,
          success(res) {
            console.log('订阅成功', res);
          },
          fail(res) {
            console.log('订阅失败', res);
          },
          complete(res) {
            console.log('订阅完成', res);
          }
        })
      }
    }
  })
}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)
  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}

//进入聊天页面(新版未上线)
function toChat(cardInfo) {
  var app = getApp();
  let nickname = cardInfo.Name;
  console.log('新版聊天', cardInfo);
  wx.request({
    url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + app.globalData.userInfo.Uid,
    success: function (res) {
      if (res.data.Code == 0 && res.data.Data) {
        let fromuid = res.data.Data.Id;
        wx.request({
          url: app.globalData.host + '/api/IM/UserByOpenId?openId=' + cardInfo.Uid,
          success: function (res2) {
            if (res2.data.Code == 0 && res2.data.Data) {
              let touid = res2.data.Data.Id;
              let chatparam = 'touid=' + touid + '&fromuid=' + fromuid + '&nickname=' + nickname + '&storeid=' + app.globalData.storeId
              wx.navigateTo({
                url: '/pages/h5page/index?url=sessionDetail.html&chatparam=' + encodeURIComponent(chatparam),
              })
            }
          }
        })
      }
    }
  })
  aiCardActionRecord(18);
}
// 关闭socket连接
function toCloseSocket() {
  wx.onSocketOpen(function() {
    wx.closeSocket()
  })
  wx.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！')
  })
}

function getUserProfile(code, cb) {
  var app = getApp();
  let flag = false;
  if (code == '') {
    wx.login({
      success: (ress) => {
        code = ress.code;
      },
    })
  }
  wx.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      console.log('用于完善会员资料', res);
      var iv = res.iv;
      var encryptedData = res.encryptedData;
      if(!encryptedData){
        wx.showToast({
          title: '授权失败,请升级微信版本',
          icon: 'none',
          mask: true
        })
      }
      // 下面开始调用注册接口
      wx.request({
        url: app.globalData.host + '/api/account/WxOpenRegister',
        data: {
          code: code,
          encryptedData: encryptedData,
          iv: iv,
          storeid: app.globalData.storeId,
          storeAppId: app.globalData.storeAppId
        }, // 设置请求的 参数
        method: 'POST',
        success: (res) => {
          if (res.data.Code == 0) {
            flag = true;
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
          cb(flag)
        }
      })
    },
    fail: (err) => {
      console.log(err);
      wx.showToast({
        title: '用户拒绝授权',
        icon: 'none'
      })
      cb(flag)
    }
  })
}

module.exports = {
  wxPromisify: wxPromisify,
  formatTime: formatTime,
  vailPhone: vailPhone,
  authori: authori,
  aiCardActionRecord: aiCardActionRecord,
  getCurrentToday: getCurrentToday,
  dateLater: dateLater,
  compareDate: compareDate,
  addFormIdMsg: addFormIdMsg,
  getMobile: getMobile,
  formatAvater: formatAvater,
  recordActionTime: recordActionTime,
  isAccredit: isAccredit,
  subscribe: subscribe,
  toChat: toChat,
  toCloseSocket: toCloseSocket,
  getUserProfile: getUserProfile
}